<template>
  <t-dialog
    :header="`${projectName}-综合评审`"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    width="80%"
    top="5%"
  >
    <div style="height: 65vh">
      <t-form ref="form" :colon="true" label-align="top" :data="formData" labelWidth="100px" :rules="rules">
      <t-form-item label="评审意见" name="teamLeaderOpinion">
        <tiny-mce-editor :key="1" v-model="formData.teamLeaderOpinion"></tiny-mce-editor>
      </t-form-item>
      <t-form-item label="签名日期" name="signDate">
        <t-date-picker :disabled="signDateDisabled" clearable style="width: 390px" v-model="formData.signDate"></t-date-picker>
      </t-form-item>
      <t-form-item label="评审意见表附件" name="dgAndYsPsYjsIds">
        <template slot="label">
          评审意见表
          <t-link hover="color" :underline="false"  style="margin-left: 24px" theme="primary"  :loading="pdfLoading" @click="projectExpertsInfoPdf" variant="outline">
            {{pdfLoading?'自动生成带签名的评审意见表中...':'自动生成评审意见表'}}
          </t-link>
          <t-popup trigger="click">
            <t-link hover="color" style="margin-left: 10px" :underline="false"  theme="primary" >扫码更新签名</t-link>
            <template #content>
              <h3>手机扫码更新签名</h3>
              <qrcode-vue  :value="qrcodeValue" :size="192" level="H" />
            </template>
          </t-popup>
        </template>
        <file-upload v-model="formData.dgAndYsPsYjsIds" accept="application/pdf" moduleKey="dgAndYsPsYjs" :fileList="dgAndYsPsYjsFiles"
                     :multiple="false" tips="">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon"/>
            上传评审意见表
          </t-button>
        </file-upload>
<!--        <a class="t-button-link" target="_blank" v-if="dgAndYsPsYjsFiles.length>0" :href="dgAndYsPsYjsFiles[0].url">-->
<!--          {{ dgAndYsPsYjsFiles[0].name }}-->
<!--        </a>-->
      </t-form-item>
      </t-form>
    </div>
    <template #footer>
      <t-button theme="default" @click="closeDialog">取消</t-button>
<!--      <t-button theme="default" variant="outline" :loading="pdfLoading" @click="projectExpertsInfoPdf">评审意见表附件预览-->
<!--      </t-button>-->
      <t-button theme="primary" :loading="loading" @click="onSubmit(1)">暂存</t-button>
      <t-button theme="primary" :loading="loading" @click="onSubmit(2)">提交</t-button>

    </template>
  </t-dialog>
</template>

<script>
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import QrcodeVue from 'qrcode.vue';
import {getToken} from "@/utils/auth";
import {getFilesByUserId} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"
import { TODAY_CN, TODAY } from '@/utils/date';

export default {
  name: "expert-leader-project-approval",
  components: {
    TinyMceEditor,
    QrcodeVue,
    FileUpload
  },
  props: ["objId", "projectName", "teamId", "projectNum", "reviewType"],
  data() {
    return {
      visible: true,
      refreshStart: false,
      signDateDisabled: false,
      dgAndYsPsYjsFiles: [],
      qrcodeValue: '',
      formData: {
        id: this.objId,
        teamLeaderOpinion: '',
        teamId: this.teamId,
        dgAndYsPsYjsIds: [],
        reviewType: this.reviewType,
        signDate: '',
      },
      pdfLoading: false,
      loading: false,
      rules: {
        teamLeaderOpinion: [
          { required: true, message: "评审意见不能为空"}
        ],
        dgAndYsPsYjsIds: [
          {required: true, validator: (val) => val && val.length, message: `评审意见表不能为空，点击自动生成评审意见表。`, type: "error"}
        ],
        signDate: [
          { required: true, message: "签名日期不能为空"}
        ],
      }
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
  },
  created() {
    this.qrcodeValue = `${window.location.origin}/online-signature/?code=${getToken()}`;
  },
  methods: {
    setTemplateValue(type){
      this.$api.kjsf.review.reviewTemplate(type).then(res => {
        if(res.data){
          // eslint-disable-next-line no-template-curly-in-string
          this.formData.teamLeaderOpinion = res.data.content.replace('${date}', TODAY_CN).replace('${projectName}', this.projectName).replace('${projectNum}', this.projectNum);
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getObj() {
      this.$api.kjsf.review.projectReviewTeamGet(this.objId).then(res => {
        if(res.data.teamLeaderOpinion){
          this.formData.teamLeaderOpinion = res.data.teamLeaderOpinion;
        }else {
          if(this.reviewType === '3'){
            this.setTemplateValue(2);
          }else {
            this.setTemplateValue(1);
          }
        }
        this.$api.kjsf.review.teamGet(this.teamId).then((response) => {
          if(response.data.reviewMeetingDate){
            this.signDateDisabled = true;
          }
          this.formData.signDate = this.formData.signDate || response.data.reviewMeetingDate || TODAY;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });
      getFilesByUserId(this.objId, this.$store.state.user.userId).then((res) => {
        const files = {}
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = []
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        const dgAndYsPsYjsFilesNow = files.dgAndYsPsYjs || [];
        if(dgAndYsPsYjsFilesNow.length>0){
          this.dgAndYsPsYjsFiles = [dgAndYsPsYjsFilesNow[0]];
        }else {
          this.dgAndYsPsYjsFiles = dgAndYsPsYjsFilesNow;
        }
        this.formData.dgAndYsPsYjsIds = this.dgAndYsPsYjsFiles.map(val => val.id)
      }).catch(e => {
        this.$message.error(e.toString())
      })

    },
    onSubmit(type) {
      if(type === 1){
        this.loading = true;
        this.$api.kjsf.review.teamLeaderOpinion({
          ...this.formData,
          sysAttMainVo: {sysAttMainIds: this.formData.dgAndYsPsYjsIds}
        }).then(res2 => {
          // 提交
          this.loading = false;
          this.$message.success("暂存成功");
          this.$emit("reload");
          this.$emit("update:visible", false);
        }).catch((e) => {
          this.loading = false;
          this.$message.error(e.toString());
        });
      }else{
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            // 生成pdf
            this.loading = true;
            this.$api.kjsf.review.teamLeaderOpinion({
              ...this.formData,
              sysAttMainVo: {sysAttMainIds: this.formData.dgAndYsPsYjsIds}
            }).then(res2 => {
              // 提交
              this.loading = false;
              this.$message.success("提交成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })
      }

    },
    projectExpertsInfoPdf() {
      this.pdfLoading = true;
      this.$api.kjsf.review.projectExpertsInfoPdf(this.formData).then(res => {
        this.dgAndYsPsYjsFiles = [
          {
            name: res.data.fileName,
            url: res.data.fullFilePath,
            id: res.data.id,
            filePath: res.data.filePath
          }
        ]
        this.formData.dgAndYsPsYjsIds = this.dgAndYsPsYjsFiles.map(val => val.id)
        this.$message.success("自动生成带签名的评审意见表成功！可点击预览");
        this.pdfLoading = false;
        // window.open(res.data.fullFilePath, '_blank')
      }).catch((e) => {
        this.pdfLoading = false;
        this.$message.error(e.toString());
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
  }
}
</script>

<style scoped>

</style>
